﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using WebLicenseGenerator.UC;
using Sinacor.Infra.Core.Licensing.Business;
using System.Collections.Generic;
using Sinacor.Infra.Common.Serialization;
using Sinacor.Infra.Core.Licensing;
using Sinacor.Infra.Common.Security.Cryptography;
using System.IO;

namespace WebLicenseGenerator
{
	public partial class NewLicense : System.Web.UI.Page
	{
		Sinacor.Infra.Core.Licensing.Business.Alias _aliasBusiness = null;
        
        Empresa _companyBusiness = null;
		Licenca _licenseBusiness = null;
        Licenca bussinesLicenca;
        List<Licensing> listaLicenca;
        List<Licensing> listaLicencaBKP;
        Confirmation _confirmation;
               
        
		int _selectedAliasCode
		{
			get
			{
				if (ViewState["SelectedAliasCode"] != null)
					return Convert.ToInt32(ViewState["SelectedAliasCode"]);
				else
					return 0;
			}
			set { ViewState["SelectedAliasCode"] = value; }
		}
		int _selectedCompanyId
		{
			get
			{
				if (ViewState["SelectedCompanyId"] != null)
					return Convert.ToInt32(ViewState["SelectedCompanyId"]);
				else
					return 0;
			}
			set { ViewState["SelectedCompanyId"] = value; }
		}

		List<Sinacor.Infra.Core.Licensing.Company> _selectedCompanyTable
		{
			get { return ViewState["FoundCompanyTable"] as List<Sinacor.Infra.Core.Licensing.Company>; }
			set { ViewState["FoundCompanyTable"] = value; }
		}
		List<Sinacor.Infra.Core.Licensing.Module> _selectedModuleTable
		{
			get { return ViewState["SelectedModuleTable"] as List<Sinacor.Infra.Core.Licensing.Module>; }
			set { ViewState["SelectedModuleTable"] = value; }
		}
		List<Sinacor.Infra.Core.Licensing.Module> _allModulesTable
		{
			get { return ViewState["AllModulesTable"] as List<Sinacor.Infra.Core.Licensing.Module>; }
			set { ViewState["AllModulesTable"] = value; }
		}

		Sinacor.Infra.Core.Licensing.Licensing _actualLicense
		{
			get { return ViewState["ActualLicense"] as Sinacor.Infra.Core.Licensing.Licensing; }
			set { ViewState["ActualLicense"] = value; }
		}
		List<Sinacor.Infra.Core.Licensing.Licensing> _actualLicenseFromDatabase
		{
			get { return ViewState["ActualLicenseFromDatabase"] as List<Sinacor.Infra.Core.Licensing.Licensing>; }
			set { ViewState["ActualLicenseFromDatabase"] = value; }
		}

		bool _isNewLicense
		{
			get
			{
				if (ViewState["IsNewLicense"] != null)
					return Convert.ToBoolean(ViewState["IsNewLicense"]);
				else
					return false;
			}
			set { ViewState["IsNewLicense"] = value; }
		}
		bool _reloadModules
		{
			get
			{
				if (ViewState["ReloadModules"] != null)
					return Convert.ToBoolean(ViewState["ReloadModules"]);
				else
					return false;
			}
			set { ViewState["ReloadModules"] = value; }
		}

		void LoadAliases()
		{
			_aliasBusiness = new Sinacor.Infra.Core.Licensing.Business.Alias();

			cbAliases.DataSource = _aliasBusiness.Selecionar(new Sinacor.Infra.Core.Licensing.Alias());
			cbAliases.DataTextField = "Nome";
			cbAliases.DataValueField = "ID";
			cbAliases.DataBind();
			cbAliases.Items.Insert(0, "");
		}

		void LoadCompanies()
		{
			_aliasBusiness = new Sinacor.Infra.Core.Licensing.Business.Alias();
			List<Sinacor.Infra.Core.Licensing.Company> selectedCompanies = _aliasBusiness.SelecionarCompaniasVinculadas(new Sinacor.Infra.Core.Licensing.Alias(_selectedAliasCode));

			lbCompanies.DataSource = selectedCompanies;
			_selectedCompanyTable = selectedCompanies;

			lbCompanies.DataTextField = "Name";
			lbCompanies.DataValueField = "CompanyId";
			lbCompanies.DataBind();

			if (_actualLicense != null)
				_actualLicense.Companies = _selectedCompanyTable;
		}

		void LoadModules()
		{
			if (_reloadModules)
			{
				_companyBusiness = new Empresa();
				_allModulesTable = _companyBusiness.RetrieveModules();
				_actualLicense.Companies = this.FilterModules(_actualLicense.Companies, _selectedCompanyId, _allModulesTable);
				_reloadModules = false;
			}

			_selectedModuleTable = this.FindModules(_selectedCompanyId);
			gvModules.DataSource = _selectedModuleTable;
			gvModules.DataBind();
		}

		void LoadLicenseTypes()
		{
			//cbLicenseType.Items.Add("");
			cbLicenseType.Items.Add(new ListItem(Sinacor.Infra.Core.Licensing.Treaty.Completa.ToString(), ((int)Sinacor.Infra.Core.Licensing.Treaty.Completa).ToString()));
			cbLicenseType.Items.Add(new ListItem(Sinacor.Infra.Core.Licensing.Treaty.Modulo.ToString(), ((int)Sinacor.Infra.Core.Licensing.Treaty.Modulo).ToString()));
			cbLicenseType.Items.Add(new ListItem(Sinacor.Infra.Core.Licensing.Treaty.Trial.ToString(), ((int)Sinacor.Infra.Core.Licensing.Treaty.Trial).ToString()));
			cbLicenseType.Items.Add(new ListItem(Sinacor.Infra.Core.Licensing.Treaty.Usuario.ToString(), ((int)Sinacor.Infra.Core.Licensing.Treaty.Usuario).ToString()));
			//cbLicenseType.SelectedIndex = -1;
		}

		void ClearGridView()
		{
			gvModules.DataSource = null;
			this.BindGridView();
		}

		void LockGridControls(bool isEnabled)
		{
			chkSelectAll.Enabled = isEnabled;
			chkStartDate.Enabled = isEnabled;
			dpExpiration.Enabled = isEnabled;
		}

		void LockButtons(bool isEnabled)
		{
			btSave.Enabled = isEnabled;
			btExport.Enabled = isEnabled;
		}

		void LockLicense(bool isEnabled)
		{
			cbLicenseType.Enabled = isEnabled;
		}

		void ClearControls()
		{			
			chkSelectAll.Checked = false;
			chkStartDate.Checked = false;

			lbCompanies.DataSource = null;
			lbCompanies.DataBind();
			lbCompanies.Items.Clear();
		}

		void BindGridView()
		{
			gvModules.DataBind();
		}

		void SetLicenseType(List<Sinacor.Infra.Core.Licensing.Licensing> licenses)
		{
			if (licenses != null && licenses.Count > 0)
			{
				switch (licenses[0].Treaty)
				{
					case Sinacor.Infra.Core.Licensing.Treaty.Trial:
						cbLicenseType.SelectedValue = "1";
						break;
					case Sinacor.Infra.Core.Licensing.Treaty.Modulo:
						cbLicenseType.SelectedValue = "2";
						break;
					case Sinacor.Infra.Core.Licensing.Treaty.Usuario:
						cbLicenseType.SelectedValue = "3";
						break;
					case Sinacor.Infra.Core.Licensing.Treaty.Completa:
						cbLicenseType.SelectedValue = "4";
						break;
				}
			}
		}

		void SetSelectedModule(int companyId, int moduleId, DateTime expiresOn)
		{
			foreach (Sinacor.Infra.Core.Licensing.Company company in _actualLicense.Companies)
			{
				if (company.CompanyId == companyId)
				{
					foreach (Sinacor.Infra.Core.Licensing.Module module in company.Modules)
					{
						if (module.ID == moduleId)
						{
							module.GoodThru = expiresOn;
							module.IsSelected = true;
							break;
						}
					}
					break;
				}
			}
		}

		void ResetSelectedModule(int companyId, int moduleId)
		{
			foreach (Sinacor.Infra.Core.Licensing.Company company in _actualLicense.Companies)
			{
				if (company.CompanyId == companyId)
				{
					foreach (Sinacor.Infra.Core.Licensing.Module module in company.Modules)
					{
						if (module.ID == moduleId)
						{
							module.GoodThru = DateTime.MinValue;
							module.IsSelected = false;
							break;
						}
					}
					break;
				}
			}
		}

		void ExportLicense()
		{
                const int KEY_SIZE = 1024;
                string filePath = Server.MapPath(@"licenses\sinacor.lic");

                Sinacor.Infra.Core.Licensing.Licensing licensing = this.GenerateFinalLicenseConfiguration();
                licensing.AliasName = cbAliases.SelectedItem.Text;

                SignedLicensing signedLicensing = new SignedLicensing();
                DsaSigner.SignedData signedData = DsaSigner.Sign(Licensing.Serialize(licensing), KEY_SIZE);

                signedLicensing.Licensing = licensing;
                signedLicensing.PublicKey = signedData.Key;
                signedLicensing.Signature = signedData.Signature;
                signedLicensing.SaveMappedLicensingFile(filePath);

                this.DownloadLicense(filePath);            
		}

		void DownloadLicense(string path)
		{
			Response.Redirect("LicenseDownload.aspx?p=" + path, false);
		}

		void ResetUnifyExpirationDate()
		{
			chkStartDate.Checked = false;
			dpExpiration.Text = "";
		}

		void SetSelectAllItems()
		{
			chkSelectAll.Checked = AreAllItemsSelected();
		}

		bool AreAllItemsSelected()
		{
			bool retorno = false;

			foreach (GridViewRow r in gvModules.Rows)
			{
				CheckBox chk = ((CheckBox)r.Cells[0].FindControl("chkIsSelected"));

				retorno = chk.Checked;

				if (!retorno)
					break;
			}

			return retorno;
		}

		List<Sinacor.Infra.Core.Licensing.Company> FilterModules(List<Sinacor.Infra.Core.Licensing.Company> companyTable, int selectedCompanyId, List<Sinacor.Infra.Core.Licensing.Module> allModules)
		{
			foreach (Sinacor.Infra.Core.Licensing.Company myCompany in companyTable)
				myCompany.Modules = (List<Sinacor.Infra.Core.Licensing.Module>)Sinacor.Infra.Common.Serialization.CloneHelper.Clone(allModules);

			foreach (Sinacor.Infra.Core.Licensing.Licensing lic in _actualLicenseFromDatabase)
			{
				foreach (Sinacor.Infra.Core.Licensing.Company company in lic.Companies)
				{
					foreach (Sinacor.Infra.Core.Licensing.Company myCompany in companyTable)
					{
						if (company.CompanyId == myCompany.CompanyId)
						{
							foreach (Sinacor.Infra.Core.Licensing.Module module in company.Modules)
							{
								foreach (Sinacor.Infra.Core.Licensing.Module myModule in myCompany.Modules)
								{
									if (myModule.ID == module.ID)
									{
										myModule.GoodThru = module.GoodThru;
										myModule.Monogram = module.Monogram;
										myModule.Name = module.Name;
										myModule.Plus = module.Plus;
										myModule.IsSelected = true;
										break;
									}
								}
							}
							break;
						}
					}
				}
			}

			return companyTable;
		}

		List<Sinacor.Infra.Core.Licensing.Module> FindModules(int companyId)
		{
			foreach (Sinacor.Infra.Core.Licensing.Company company in _actualLicense.Companies)
			{
				if (company.CompanyId == companyId)
					return company.Modules;
			}

			return new List<Sinacor.Infra.Core.Licensing.Module>(); ;
		}

		Sinacor.Infra.Core.Licensing.Licensing GenerateFinalLicenseConfiguration()
		{
			Sinacor.Infra.Core.Licensing.Licensing finalLicense = (Sinacor.Infra.Core.Licensing.Licensing)CloneHelper.Clone(_actualLicense);

			List<Sinacor.Infra.Core.Licensing.Company> companiesToRemove = new List<Sinacor.Infra.Core.Licensing.Company>();

			foreach (Sinacor.Infra.Core.Licensing.Company company in finalLicense.Companies)
			{
				List<Sinacor.Infra.Core.Licensing.Module> modulesToRemove = new List<Sinacor.Infra.Core.Licensing.Module>();

				foreach (Sinacor.Infra.Core.Licensing.Module module in company.Modules)
				{
					if (!module.IsSelected)
						modulesToRemove.Add(module);
					else
						module.Plus = true;
				}

				for (int i = 0; i < modulesToRemove.Count; i++)
					company.Modules.Remove(modulesToRemove[i]);

				if (company.Modules.Count <= 0)
					companiesToRemove.Add(company);
			}

			for (int j = 0; j < companiesToRemove.Count; j++)
				finalLicense.Companies.Remove(companiesToRemove[j]);

			return finalLicense;
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				this.LoadAliases();
				this.LoadLicenseTypes();                

                if (Request.QueryString["licenseId"] != null)
                {
                    int id = Convert.ToInt16(Request.QueryString["licenseId"]);
                    int AliasId = Convert.ToInt16(Request.QueryString["AliasId"]);
                    int IdCorr = Convert.ToInt16(Request.QueryString["IdCorr"]);
                    String tipoLic = Request.QueryString["tipoLic"];

                    cbAliases.SelectedValue = Convert.ToString(AliasId);
                    lbCompanies.SelectedValue = Convert.ToString(IdCorr);
                    cbLicenseType.SelectedValue = tipoLic;
                    
                    cbAliases_SelectedIndexChanged(cbAliases,e);
                    cbLicenseType_SelectedIndexChanged(cbLicenseType, e);
                    lbCompanies_SelectedIndexChanged(lbCompanies, e);
                }
			}

            this.Submit1.ServerClick += new System.EventHandler(this.Submit1_ServerClick);
            _confirmation = ((WebLicenseGenerator.UC.Confirmation)this.Master.FindControl("confirmationPanel"));
            _confirmation.OnConfirmation += new Confirmation.ConfirmationEventHandler(OnConfirmation);
		}

		protected void cbAliases_SelectedIndexChanged(object sender, EventArgs e)
		{
			_isNewLicense = true;
			_selectedAliasCode = 0;
			_reloadModules = true;

			DropDownList ddl = ((DropDownList)sender);

			if (ddl.SelectedIndex == 0)
			{
				this.ClearGridView();
				this.ClearControls();
				this.LockGridControls(false);
				this.LockButtons(false);
				this.LockLicense(false);
				ddl.Focus();
			}
			else
			{
				_selectedAliasCode = Int32.Parse(ddl.SelectedItem.Value);
				_licenseBusiness = new Licenca();

				Sinacor.Infra.Core.Licensing.Licensing lic = new Sinacor.Infra.Core.Licensing.Licensing();
				lic.Id = null;
				lic.Created = null;
				lic.Treaty = null;
				lic.AliasId = _selectedAliasCode;
				_actualLicenseFromDatabase = _licenseBusiness.Selecionar(lic);

				if (_actualLicenseFromDatabase.Count > 0)
				{
					_isNewLicense = false;

					_actualLicense = new Sinacor.Infra.Core.Licensing.Licensing();
					_actualLicense.AliasId = _selectedAliasCode;
					_actualLicense.Id = _actualLicenseFromDatabase[0].Id;
					_actualLicense.Treaty = _actualLicenseFromDatabase[0].Treaty;
					_actualLicense.Created = _actualLicenseFromDatabase[0].Created;
					_actualLicense.Active = _actualLicenseFromDatabase[0].Active;

					this.SetLicenseType(_actualLicenseFromDatabase);
				}
				else
				{
					_actualLicense = new Sinacor.Infra.Core.Licensing.Licensing();
					_actualLicense.AliasId = _selectedAliasCode;
					_actualLicense.Created = DateTime.Now;
					_actualLicense.Active = Sinacor.Infra.Core.Licensing.Active.Ativo;

					switch (cbLicenseType.SelectedValue)
					{
						case "1":
							_actualLicense.Treaty = Sinacor.Infra.Core.Licensing.Treaty.Trial;
							break;
						case "2":
							_actualLicense.Treaty = Sinacor.Infra.Core.Licensing.Treaty.Modulo;
							break;
						case "3":
							_actualLicense.Treaty = Sinacor.Infra.Core.Licensing.Treaty.Usuario;
							break;
						case "4":
							_actualLicense.Treaty = Sinacor.Infra.Core.Licensing.Treaty.Completa;
							break;
					}

					//this.SetLicenseType();
				}

				this.ClearGridView();
				this.LoadCompanies();
				this.LockButtons(true);
				this.LockLicense(true);
			}
		}

		protected void lbCompanies_SelectedIndexChanged(object sender, EventArgs e)
		{
			_selectedCompanyId = 0;

			ListBox lb = ((ListBox)sender);

			if (lb.SelectedIndex < 0)
			{
				this.ClearGridView();
				this.LockGridControls(false);
			}
			else
			{
				_selectedCompanyId = Int32.Parse(lb.SelectedItem.Value);
				this.LoadModules();
				this.LockGridControls(true);
			}

			this.ResetUnifyExpirationDate();
			this.SetSelectAllItems();
		}

		protected void dpExpiration_TextChanged(object sender, EventArgs e)
		{
			if (chkStartDate.Checked)
			{
				foreach (GridViewRow r in gvModules.Rows)
				{
					if (sender is TextBox)
					{
						string dateTime = ((TextBox)sender).Text;

						CheckBox chk = ((CheckBox)r.Cells[0].FindControl("chkIsSelected"));
						int moduleId = Convert.ToInt32(chk.Attributes["ModuleId"]);

						((MaskedDate)r.Cells[2].FindControl("dpExpirationDate")).Text = dateTime;
						DateTime expiresOn = new DateTime(Int32.Parse(dateTime.Substring(6, 4)), Int32.Parse(dateTime.Substring(3, 2)), Int32.Parse(dateTime.Substring(0, 2)));

						this.SetSelectedModule(_selectedCompanyId, moduleId, expiresOn);
					}
				}
			}
		}

		protected void chkSelectAll_CheckedChanged(object sender, EventArgs e)
		{
			foreach (GridViewRow r in gvModules.Rows)
			{
				bool isChecked = ((CheckBox)sender).Checked;
				CheckBox chk = ((CheckBox)r.Cells[0].FindControl("chkIsSelected"));
				chk.Checked = isChecked;
				int moduleId = Convert.ToInt32(chk.Attributes["ModuleId"]);

				MaskedDate dt = ((MaskedDate)r.Cells[2].FindControl("dpExpirationDate"));

				if (isChecked)
				{
					dt.Text = DateTime.Today.AddYears(1).ToString("dd/MM/yyyy");
					DateTime expiresOn = DateTime.Today.AddYears(1);
					this.SetSelectedModule(_selectedCompanyId, moduleId, expiresOn);
				}
				else
				{
					dt.Text = "";
					this.ResetSelectedModule(_selectedCompanyId, moduleId);
				}
			}
		}

		protected void chkExpiration_CheckedChanged(object sender, EventArgs e)
		{
			foreach (GridViewRow r in gvModules.Rows)
			{
				bool isChecked = ((CheckBox)sender).Checked;
				CheckBox chk = ((CheckBox)r.Cells[0].FindControl("chkIsSelected"));
				int moduleId = Convert.ToInt32(chk.Attributes["ModuleId"]);

				MaskedDate dt = ((MaskedDate)r.Cells[2].FindControl("dpExpirationDate"));

				if (isChecked)
				{
					if (String.IsNullOrEmpty(dpExpiration.Text))
						dpExpiration.Text = DateTime.Today.AddYears(1).ToString("dd/MM/yyyy");

					string dateTime = dpExpiration.Text;
					dt.Text = dateTime;
					DateTime expiresOn = new DateTime(Int32.Parse(dateTime.Substring(6, 4)), Int32.Parse(dateTime.Substring(3, 2)), Int32.Parse(dateTime.Substring(0, 2)));
					this.SetSelectedModule(_selectedCompanyId, moduleId, expiresOn);
				}
				else
				{
					dt.Text = "";
					this.ResetSelectedModule(_selectedCompanyId, moduleId);
				}
			}
		}

		protected void cbLicenseType_SelectedIndexChanged(object sender, EventArgs e)
		{
			switch (cbLicenseType.SelectedValue)
			{
				case "1":
					_actualLicense.Treaty = Sinacor.Infra.Core.Licensing.Treaty.Trial;
					break;
				case "2":
					_actualLicense.Treaty = Sinacor.Infra.Core.Licensing.Treaty.Modulo;
					break;
				case "3":
					_actualLicense.Treaty = Sinacor.Infra.Core.Licensing.Treaty.Usuario;
					break;
				case "4":
					_actualLicense.Treaty = Sinacor.Infra.Core.Licensing.Treaty.Completa;
					break;
			}
		}

		protected void chkModuleChanged(object sender, EventArgs e)
		{
			if (sender is CheckBox)
			{
				bool isChecked = ((CheckBox)sender).Checked;

				MaskedDate dt = ((MaskedDate)gvModules.Rows[Convert.ToInt32(((CheckBox)sender).Attributes["RowIndex"])].Cells[2].FindControl("dpExpirationDate"));

				if (isChecked)
				{
					dt.Text = DateTime.Today.AddYears(1).ToString("dd/MM/yyyy");
					DateTime expiresOn = DateTime.Today.AddYears(1);

					int moduleId = Convert.ToInt32(((CheckBox)sender).Attributes["ModuleId"]);
					this.SetSelectedModule(_selectedCompanyId, moduleId, expiresOn);
				}
				else
				{
					dt.Text = "";
					int moduleId = Convert.ToInt32(((CheckBox)sender).Attributes["ModuleId"]);
					this.ResetSelectedModule(_selectedCompanyId, moduleId);
				}

				this.SetSelectAllItems();
			}
		}

		protected void gvModules_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				CheckBox rd = ((CheckBox)e.Row.Cells[0].FindControl("chkIsSelected"));
				rd.Attributes.Add("RowIndex", e.Row.RowIndex.ToString());

				Sinacor.Infra.Core.Licensing.Module module = (Sinacor.Infra.Core.Licensing.Module)e.Row.DataItem;
				rd.Attributes.Add("ModuleId", module.ID.ToString());
			}
		}
        
		protected void btSave_Click(object sender, EventArgs e)
		{
            if (cbAliases.SelectedValue != null && cbAliases.SelectedValue != "")
            {
                if (Convert.ToBoolean(Session["isImport"]) == true)
                    //Define se vai ou nao querer gravar o arquivo importado
                    ShowConfirmationDialog("Titulo", "Texto");
                else
                    Save();                
            }
            else
            {
                this.ShowMessageDialog("Salvar Licença", "Campo Alias deve ser informado.");
                cbAliases.Focus();
            }   
		}

        protected void Save()
        {            
                Sinacor.Infra.Core.Licensing.Licensing lic = this.GenerateFinalLicenseConfiguration();
                lic.Description.Period = DateTime.Now;
                lic.Description.User = System.Environment.UserName;

                _licenseBusiness = new Licenca();

                if (_isNewLicense)
                {
                    lic.Description.TypeDescription = Sinacor.Infra.Core.Licensing.TypeDescription.Incluir;
                    _licenseBusiness.Incluir(lic);
                    this.ShowMessageDialog("Nova Licença", "Licença criada com sucesso.");
                }
                else
                {
                    lic.Description.TypeDescription = Sinacor.Infra.Core.Licensing.TypeDescription.Alterar;
                    _licenseBusiness.Alterar(lic);
                    this.ShowMessageDialog("Alteração de Licença", "Licença salva com sucesso.");
                }
        }

		protected void btExport_Click(object sender, EventArgs e)
		{
            if (cbAliases.SelectedValue != null && cbAliases.SelectedValue != "")
                this.ExportLicense();               
            else
            {
                this.ShowMessageDialog("Exportação de Licença", "Campo Alias deve ser informado.");
                cbAliases.Focus();
            }            			         
		}

        protected void ImportLicense(String CaminhoArquivo) 
        {
            //Bloco que decriptografa o arquivo XML e tras os dados
            SignedLicensing signedLicensing;
            signedLicensing = new SignedLicensing();
            signedLicensing.LoadMappedLicensingFile(CaminhoArquivo);
            //signedLicensing.LoadMappedLicensingFile();
            
            //variaveis usada para guardar valores capturados do XML
            string aliasName = null, tipoLicensa = null, cnpj = null, empresa = null, modulo = null;
            int idSinacor;
            
            //Verifica se o Alias vindo do Xml tem dado
            if (signedLicensing.Licensing.AliasName != null)
            {
                aliasName = Convert.ToString(signedLicensing.Licensing.AliasName);
                
                Sinacor.Infra.Core.Licensing.Alias _alias = new Sinacor.Infra.Core.Licensing.Alias();
                _alias.Nome = aliasName;

                //Se Alias existir, captura id pra selecionar na combo Alias
                //Caso contrário, cria um novo Alias
                if (VerificarAliasExiste(aliasName))
                {   
                    _alias = SelecionarAlias(_alias);
                    cbAliases.SelectedValue = Convert.ToString(_alias.ID);
                }
                else
                {
                    InsertNewAlias(aliasName);
                }
                
                _selectedAliasCode = Convert.ToInt16(cbAliases.SelectedValue);
            }

            //Verifica se o Tipo da licença vindo do Xml tem dado
            if (signedLicensing.Licensing.Treaty != null)
            {
                tipoLicensa = Convert.ToString(signedLicensing.Licensing.Treaty);
                cbLicenseType.SelectedItem.Text = tipoLicensa;
            }

            //Verifica se a Empresa vinda do Xml tem dado
            if (signedLicensing.Licensing.Companies.Count > 0)
            {
                Sinacor.Infra.Core.Licensing.Business.Empresa _businnesCompany = new Sinacor.Infra.Core.Licensing.Business.Empresa();
                Sinacor.Infra.Core.Licensing.Company _company = new Sinacor.Infra.Core.Licensing.Company();

                //captura dados referente a empresa
                empresa = Convert.ToString(signedLicensing.Licensing.Companies[0].Name);
                cnpj = Convert.ToString(signedLicensing.Licensing.Companies[0].LegalRegistrationId);
                idSinacor = Convert.ToInt16(signedLicensing.Licensing.Companies[0].SinacorCompanyId);

                _company.Name = empresa;
                _company.LegalRegistrationId = cnpj;

                //Se Empresa existir, captura id pra selecionar na lista de empresas
                //Caso contrário, cria uma nova Empresa e Vincula a mesma ao Alias
                if (VerificarEmpresaExiste(empresa, cnpj))
                {
                    cbAliases_SelectedIndexChanged(cbAliases, null);

                    _company = _businnesCompany.SelecionarCodEmpresa(_company);
                    lbCompanies.SelectedValue = Convert.ToString(_company.CompanyId);
                    lbCompanies_SelectedIndexChanged(lbCompanies, null);
                }
                else
                {
                    InsertNewCompany(empresa, cnpj, idSinacor);
                }
            }

            //Verifica se os móduloes vindo do Xml tem dados
            if (signedLicensing.Licensing.Companies[0].Modules.Count > 0)
            {
                //loop passando por todos os módulos encontrados para a empresa
                for (int i = 0; i < signedLicensing.Licensing.Companies[0].Modules.Count; i++)
                {
                    //captura valor do Módulo
                    modulo = Convert.ToString(signedLicensing.Licensing.Companies[0].Modules[i].Name);
                    //loop percorrendo o grid para marcar os módulos encontrados
                    //desta maneira, é feita a validação de que só módulos realmente válidos serão enviados para o banco
                    foreach (GridViewRow r in gvModules.Rows)
                    {
                        if (modulo == r.Cells[1].Text)
                        {
                            CheckBox chk = ((CheckBox)r.Cells[0].FindControl("chkIsSelected"));
                            chk.Checked = true;
                            chkModuleChanged(chk, null);                            
                            break;
                        }
                    }
                }
            }         
        }

        void ShowMessageDialog(string title, string message)
		{
			WebLicenseGenerator.UC.Messaging messaging = ((WebLicenseGenerator.UC.Messaging)this.Master.FindControl("errorMessaging"));
			messaging.Message = message;
			messaging.Title = title;
			messaging.ShowMessageDialog();
            
		}

        void ShowConfirmationDialog(string title, string message)
        {
            _confirmation.Message = message;
            _confirmation.Title = title;
            _confirmation.ShowConfirmationDialog();
        }

        void OnConfirmation(object sender, ConfirmationEventArgs e)
        {
            if (e.Result == ConfirmationResult.Yes)
            {
                Save();                
            }
            Session["isImport"] = false;
        }

        private bool VerificarAliasExiste(String Alias)
        {
            Sinacor.Infra.Core.Licensing.Alias _alias = new Sinacor.Infra.Core.Licensing.Alias();
            _aliasBusiness = new Sinacor.Infra.Core.Licensing.Business.Alias();

            _alias.Nome = Alias;
            return _aliasBusiness.VerificarAliasExiste(_alias);
        }

        private void InsertNewAlias(String alias)
        {
            _aliasBusiness = new Sinacor.Infra.Core.Licensing.Business.Alias();
            _aliasBusiness.Incluir(new Sinacor.Infra.Core.Licensing.Alias(alias));
        }

        private Sinacor.Infra.Core.Licensing.Alias SelecionarAlias(Sinacor.Infra.Core.Licensing.Alias library)
        { 
             _aliasBusiness = new Sinacor.Infra.Core.Licensing.Business.Alias();

             return _aliasBusiness.SelecionarCodAlias(library);
        }

        private bool VerificarEmpresaExiste(String CompanyName,String LegalRegistrationId)
        {
            Sinacor.Infra.Core.Licensing.Company _company = new Sinacor.Infra.Core.Licensing.Company();
            _companyBusiness = new Sinacor.Infra.Core.Licensing.Business.Empresa();

            _company.Name = CompanyName;
            _company.LegalRegistrationId = LegalRegistrationId;

            return _companyBusiness.VerificarEmpresaExiste(_company);
        }

        private void InsertNewCompany(String CompanyName, String Cnpj,int CompanySinacorId)
        {
            Sinacor.Infra.Core.Licensing.Company newCompany = new Sinacor.Infra.Core.Licensing.Company(CompanyName, Cnpj, 0);
            newCompany.SinacorCompanyId = CompanySinacorId;

            _aliasBusiness = new Sinacor.Infra.Core.Licensing.Business.Alias();
            _aliasBusiness.IncluirNovaCompanhia(new Sinacor.Infra.Core.Licensing.Alias(_selectedAliasCode), newCompany);
            
        }     

        private void Submit1_ServerClick(object sender, System.EventArgs e)
        {
            Session["isImport"] = false;

            if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
            {
                string Arquivo = System.IO.Path.GetFileName(File1.PostedFile.FileName);
                string CaminhoServer = "\\\\sinacordes1\\d$\\Ferramentas\\WebLicenseGenerator\\licenses\\sinacor.lic";
                string CaminhoLocal = File1.PostedFile.FileName;

                File1.PostedFile.SaveAs(CaminhoServer);

                if (Arquivo.Contains(".lic"))
                {
                    ImportLicense(CaminhoServer);
                    Session["isImport"] = true;
                }
                else
                    this.ShowMessageDialog("Visualização de Licença", "Arquivo carregado, não é um arquivo de licença no formato válido");
            }
            else
                this.ShowMessageDialog("Visualização de Licença", "Licença Deve ser carregada.");
        }   

	}
}